package com.peiqi.aiproject.service;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.peiqi.aiproject.domain.VerificationCode;
import com.peiqi.aiproject.domain.dto.ValidSmsDTO;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class SmsService {
//    远程缓存redis,mongo，本地缓存
    private final Cache<String, VerificationCode> codeCache= CacheBuilder.newBuilder()
        .expireAfterWrite(1, TimeUnit.MINUTES)
        .build();

    /**
     * 发送短信验证码
     * @param phoneNumber 手机号
     * @return code 短信验证码
     */
    public String sendSms(String phoneNumber) {
        String code = genRandomCode();
        VerificationCode verificationCode =
                new VerificationCode(phoneNumber,code, LocalDateTime.now().plusMinutes(1));
        codeCache.put(phoneNumber,verificationCode);
        return code;
    }
    private String genRandomCode(){
        Random random =new Random();
        //0-1
        //1-10
        int code = random.nextInt(9000)+1000;
        return String.valueOf(code);
    }

    public boolean validSms(ValidSmsDTO validSmsDTO) {
        String phoneNumber = validSmsDTO.getPhoneNumber();
        VerificationCode verificationCode = codeCache.getIfPresent(phoneNumber);
        if(verificationCode==null){
            return false;
        }
        String code = verificationCode.getCode();
        return code!=null && code.equals(validSmsDTO.getCode()) && verificationCode.getExpirationTime().isAfter(LocalDateTime.now());
    }
}
